//
//  ChatViewController.m
//  觅影
//
//  Created by  陶虹 on 16/4/10.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "ChatViewController.h"

@interface ChatViewController ()<UITextViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UIButton *sendButton;
@property (nonatomic, strong) EMConversation *conversation;
@property (nonatomic, strong) NSString *myName;
@property (nonatomic, strong) UIView *myView;

@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = self.buddy.username;
    self.edgesForExtendedLayout = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"头像"] style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction:)];
    self.navigationController.navigationItem.rightBarButtonItem = rightBarButton;
    
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithTitle:@"<<" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonAction:)];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT - 64)];
    self.myView.backgroundColor = [UIColor colorWithRed:210/255.0 green:213/255.0 blue:219/255.0 alpha:1];
    [self.view addSubview:_myView];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT - 50 - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    [self.myView addSubview:_tableView];
    
    self.textView = [[UITextView alloc] initWithFrame:CGRectMake(10, KHEIGHT - 64 - 50 + 10, KWIDTH - 30 - 80, 30)];
    self.textView.layer.cornerRadius = 5;
    self.textView.delegate = self;
    [self.myView addSubview:_textView];
    
    self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake(KWIDTH - 90, KHEIGHT - 64 - 50 + 10, 80, 30)];
    [self.sendButton addTarget:self action:@selector(sendButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.sendButton.backgroundColor = [UIColor blueColor];
    [self.sendButton setTitle:@"发送" forState:UIControlStateNormal];
    self.sendButton.layer.cornerRadius = 5;
    [self.myView addSubview:_sendButton];
    
    self.myName = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    // 键盘出现或者改变时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // 添加EaseMob代理
    [[EaseMob sharedInstance].chatManager addDelegate:(id)self delegateQueue:dispatch_get_main_queue()];
}

- (void)leftBarButtonAction:(UIBarButtonItem *)leftBarButton{
    // 移除通知中心
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    // 移除代理
    [[EaseMob sharedInstance].chatManager removeDelegate:(id)self];
    [self.navigationController popViewControllerAnimated:YES];
}

// 点击空白处 键盘消失
- (void)tapAction:(UITapGestureRecognizer *)tap{
    [self.textView resignFirstResponder];
}

#pragma mark --- 键盘出线和消失的通知方法 --
// 键盘出现或者改变时自动调用
- (void)keyboardWillShow:(NSNotification *)notification{
    // 获取键盘高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    CGFloat keyboardHeight = keyboardRect.size.height;
    
    [self viewMoveUpAnimation:keyboardHeight];
}

- (void)keyboardWillHide:(NSNotification *)notification{

    [self viewMoveUpAnimation:0];
}

- (void)viewMoveUpAnimation:(CGFloat)height{
    [UIView animateWithDuration:0.5 animations:^{
        self.myView.frame = CGRectMake(0, - height, KWIDTH, KHEIGHT - 64);
    }];
    
    [_tableView layoutIfNeeded];// 给tableview重新布局
    if ([_conversation loadAllMessages].count > 1) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_conversation.loadAllMessages.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
}

#pragma mark --- send message ---
- (void)sendMessage{
    EMChatText *chatText = [[EMChatText alloc] initWithText:self.textView.text];
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithChatObject:chatText];
    
    // 生成message 消息构造体
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.buddy.username bodies:@[body]];
    message.messageType = eMessageTypeChat;// 设置为单聊消息
    
    [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error) {
        NSLog(@"准备发送");
    } onQueue:dispatch_get_main_queue() completion:^(EMMessage *message, EMError *error) {
        [self reloadChatRecords];
        NSLog(@"发送完成");
    } onQueue:dispatch_get_main_queue()];
}

#pragma mark --- receive message ---
- (void)didReceiveMessage:(EMMessage *)message{
    [self reloadChatRecords];
}

#pragma mark --- reloadChatRecord ---
// 重新加载tableView上面显示的内容，并移动到最后一行
- (void)reloadChatRecords{
    _conversation = [[EaseMob sharedInstance].chatManager conversationForChatter:self.buddy.username conversationType:eConversationTypeChat];
    [_tableView reloadData];
    
    if ([_conversation loadAllMessages].count > 0) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_conversation loadAllMessages].count - 1 inSection:0] atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
    }
}

// 查看朋友信息按钮
- (void)rightButtonAction:(UIBarButtonItem *)rightBarButton{
    
}

// 发送消息
- (void)sendButtonAction:(UIButton *)button {
    [self sendMessage];
    [self.textView resignFirstResponder];
}

#pragma mark -- tableView代理方法 --
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _conversation.loadAllMessages.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithFrame:CGRectZero];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    EMMessage *message = _conversation.loadAllMessages[indexPath.row];
    EMTextMessageBody *body = [message.messageBodies lastObject];
    
    // 判断发送的是否是当前聊天的人，左边是对面发过来的，右边是自己发过去的
    if ([message.to isEqualToString:self.buddy.username]) {
        cell.detailTextLabel.text = body.text;
        cell.detailTextLabel.backgroundColor = [UIColor blueColor];
        cell.textLabel.text = @"";
    }else{
        cell.textLabel.text = body.text;
        cell.textLabel.backgroundColor = [UIColor redColor];
        cell.detailTextLabel.text = @"";
    }
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
